import { useState } from "react";

function Square({value, onSquareHanle}) {
  return (
    <button className="square" onClick={onSquareHanle}>
      {value}
    </button>
  );  
}

export default function Board() {
  const [isXNext,setIsXNext] = useState(true);
  const [squares, setSquares] = useState(Array(9).fill(null));

  function squareHanle(i) {
    if (squares[i] || calculateWinner(squares)){return;}
    const newSquares = squares.slice();
    if (isXNext) {
      newSquares[i] = 'X';
    }else {
      newSquares[i] = 'O';
    }
    setSquares(newSquares);
    setIsXNext(!isXNext);
  }

  const winner = calculateWinner(squares);
  let status;
  if (winner) {
    status = 'Winner:' + winner;
  }else {
    status = 'Next player:' + (isXNext ? 'X':'O');
  }

  return (
    <>
      <div className="status">{status}</div>
      <div className="board-row">
        <Square value={squares[0]} onSquareHanle={() => squareHanle(0)}/>
        <Square value={squares[1]} onSquareHanle={() => squareHanle(1)}/>
        <Square value={squares[2]} onSquareHanle={() => squareHanle(2)}/>
      </div>
      <div className="board-row">
        <Square value={squares[3]} onSquareHanle={() => squareHanle(3)}/>
        <Square value={squares[4]} onSquareHanle={() => squareHanle(4)}/>
        <Square value={squares[5]} onSquareHanle={() => squareHanle(5)}/>
      </div>
      <div className="board-row">
        <Square value={squares[6]} onSquareHanle={() => squareHanle(6)}/>
        <Square value={squares[7]} onSquareHanle={() => squareHanle(7)}/>
        <Square value={squares[8]} onSquareHanle={() => squareHanle(8)}/>
      </div>
    </>
  );
}


function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let index = 0; index < lines.length; index++) {
    const [a,b,c] = lines[index];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}